package com.xsp.dao;

import com.xsp.util.DBHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;

/**
 * @author xsp
 * @date 2024/1/22
 * @desc 模拟银行转账业务
 */
public class BankDao1 {
    public void transferMoney() {
        Connection connection = null;
        PreparedStatement statement1 = null;
        PreparedStatement statement2 = null;
        try {
            connection = DBHelper.getConnection();
            // 关闭自动提交
            connection.setAutoCommit(false);
            String sql1 = "update bank set money=money-? where id=?";
            String sql2 = "update bank set money=money+? where id=?";
            statement1 = connection.prepareStatement(sql1);
            statement2 = connection.prepareStatement(sql2);
            // 张三扣钱
            statement1.setObject(1, 100);
            statement1.setObject(2, 1);
            statement1.executeUpdate();
            // 模拟异常
            int a = 10 / 0;
            // 加钱
            statement2.setObject(1, 100);
            statement2.setObject(2, 2);
            statement2.executeUpdate();
            // 全部执行成功后，提交事务
            connection.commit();
            connection.setAutoCommit(true);
            System.out.println("转账成功");
        } catch (Exception e) {
            try {
                if (connection != null) {
                    connection.rollback();
                    System.out.println("发生异常，转账撤销");
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        } finally {
            try {
                DBHelper.close(statement1, null);
                DBHelper.close(statement1, connection);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
